using MediatR;
using WorkOrder.Domain;
using B.S.BaseData.Api.Read.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;

namespace B.S.BaseData.Api.Read.CommandHandler.OrderCommandHandler
{
    /// <summary>
    /// 退款申请查询处理器
    /// </summary>
    public class RefundApplicationHandler : IRequestHandler<RefundApplicationQueryCommand, APIResult<ApiPaging<RefundApplication>>>
    {
        private readonly IBaseRepository<RefundApplication> _refundRepository;

        public RefundApplicationHandler(IBaseRepository<RefundApplication> refundRepository)
        {
            _refundRepository = refundRepository;
        }

        public Task<APIResult<ApiPaging<RefundApplication>>> Handle(RefundApplicationQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPaging<RefundApplication>> result = new APIResult<ApiPaging<RefundApplication>>();
            result.Code = ApiEnum.Success;
            result.Msg = "查询成功";

            var list = _refundRepository.GetAll();

            // 如果没有数据，生成测试数据
            if (!list.Any())
            {
                list = GenerateTestData().AsQueryable();
            }
            Console.WriteLine($"原始数据数量: {list.Count()}");

            // 按时间范围筛选
            if (request.Begin != null && request.End != null)
            {
                list = list.Where(a => a.ApplicationTime >= request.Begin && a.ApplicationTime <= request.End.Value.AddDays(1));
                Console.WriteLine($"按时间筛选后数量: {list.Count()}");
            }

            // 按申请状态筛选
            if (!string.IsNullOrEmpty(request.ApplicationStatus))
            {
                list = list.Where(a => a.ApplicationStatus == request.ApplicationStatus);
                Console.WriteLine($"按申请状态筛选后数量: {list.Count()}");
            }

            // 按搜索关键词筛选（用户名或订单编号）
            if (!string.IsNullOrEmpty(request.SearchKeyword))
            {
                list = list.Where(a => a.UserName.Contains(request.SearchKeyword) || a.OrderNumber.Contains(request.SearchKeyword));
                Console.WriteLine($"按搜索关键词筛选后数量: {list.Count()}");
            }

            // 分页处理
            var totalCount = list.Count();
            var row = list.OrderByDescending(a => a.ApplicationTime)
                         .Skip((request.PageIndex - 1) * request.PageSize)
                         .Take(request.PageSize)
                         .ToList();

            Console.WriteLine($"分页后数量: {row.Count()}, PageIndex: {request.PageIndex}, PageSize: {request.PageSize}");

            var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            var page = new ApiPaging<RefundApplication>
            {
                Total = totalCount,
                TotalPage = totalPage,
                PageData = row
            };

            result.Data = page;
            return Task.FromResult(result);
        }

        /// <summary>
        /// 生成测试数据
        /// </summary>
        /// <returns></returns>
        private List<RefundApplication> GenerateTestData()
        {
            var testData = new List<RefundApplication>();
            var statuses = new[] { "待处理", "已处理", "已拒绝" };
            var sources = new[] { "挂号预约", "图文回诊", "视频回诊", "电话回诊" };
            var refundMethods = new[] { "原路退回", "微信退款", "支付宝退款", "银行卡退款" };
            var refundTypes = new[] { "全额退款", "部分退款", "手续费退款" };
            var refundReasons = new[] { "患者取消", "医生取消", "系统故障", "重复支付", "服务未完成" };
            var users = new[] { "张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十" };

            for (int i = 1; i <= 30; i++)
            {
                var status = statuses[i % statuses.Length];
                var applicationTime = DateTime.Now.AddDays(-i);

                var refund = new RefundApplication
                {
                    RefundId = $"REF20240801{i:D6}",
                    ServiceNumber = $"SVC{i:D6}",
                    OrderNumber = $"ORD20240801{i:D6}",
                    UserName = users[i % users.Length],
                    ApplicationStatus = status,
                    ApplicationTime = applicationTime,
                    OrderAmount = 100 + i * 20,
                    ActualRefundAmount = 100 + i * 20,
                    RefundMethod = refundMethods[i % refundMethods.Length],
                    RefundType = refundTypes[i % refundTypes.Length],
                    RefundReason = refundReasons[i % refundReasons.Length],
                    Source = sources[i % sources.Length],
                    ProcessorName = status != "待处理" ? "处理员" + (i % 5 + 1) : null,
                    ProcessTime = status != "待处理" ? applicationTime.AddDays(1) : null,
                    ProcessRemarks = status != "待处理" ? "已处理完成" : null,
                    CreateTime = applicationTime,
                    UpdateTime = status != "待处理" ? applicationTime.AddDays(1) : null
                };

                testData.Add(refund);
            }

            return testData;
        }
    }
} 